package com.wcity.manage.web.community;

import com.wcity.manage.common.context.Constants;
import com.wcity.manage.common.context.SessionKey;
import com.wcity.manage.common.enums.SaveImageType;
import com.wcity.manage.common.utils.DwzUtil;
import com.wcity.manage.common.utils.RespUtil;
import com.wcity.manage.common.utils.request.RequestUtil;
import com.wcity.manage.common.vo.community.guide.GuideVo;
import com.wcity.manage.dao.dal.model.PageModel;
import com.wcity.manage.dao.model.User;
import com.wcity.manage.dao.model.community.guide.Guide;
import com.wcity.manage.dao.model.community.image.ImageUrl;
import com.wcity.manage.service.community.guide.GuideService;
import com.wcity.manage.service.community.image.ImageService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 指南类别
 * Created by hgg on 2016/12/20.
 */
@Controller
public class GuideAct {

    private final static Logger log = LoggerFactory.getLogger(GuideAct.class);

    @Autowired
    private GuideService guideService;
    @Autowired
    private ImageService imageService;

    /**
     * 指南类别列表
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/community_guide_list")
    public String guideList( HttpServletRequest request, PageModel model,HttpServletResponse response ) {

        try {

            //【1】封装参数/参数校验
            Map<String, Object> requestMap = RequestUtil.getGetData(request);

            //【2】获取当前用户信息
            User user = (User)request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if( user == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【3】查询数据
            requestMap.put( "start", ( model.getPageNum() - 1) * model.getNumPerPage() );
            requestMap.put( "end", model.getNumPerPage() );
            requestMap.put( "userId", user.getId() );
            requestMap.put( "saveType",SaveImageType.COMMUNITY_GUIDE );
            List<GuideVo> guideVos = guideService.guidePageList(requestMap);

            //【4】查询总数量
            Integer totalGuide = guideService.totalGuide( requestMap );
            model.setTotal( totalGuide );

            request.setAttribute( "guides", guideVos );
            request.setAttribute( "pageModel", model );
            request.setAttribute( "guideName", requestMap.get( "guideName" ) );
        } catch ( Exception e ) {
            log.error( "查询指南类别列表异常:" + e.getMessage() );
        }
        return "community/guide/list";
    }

    /**
     * 执行删除指南类别
     *
     * @param request
     */
    @RequestMapping(value = "delete_community_guide")
    @ResponseBody
    public void deleteGuide( HttpServletRequest request, HttpServletResponse response ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "删除成功";
        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if (requestMap.get("id") == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "请选择一条记录", "", "", "", ""));
                return;
            }

            //【2】执行删除
            Integer deleteNum = guideService.deleteGuide( requestMap );
            if ( deleteNum == 0 ) {
                code = Constants.STATUS_ERROR_DWZ;
                message = "删除失败";
            }
        } catch ( Exception e ) {
            log.error( "删除指南类别异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "删除失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, message, "", "", "", ""));
    }

    /**
     * 新增指南类别
     *
     * @param guide
     * @param response
     */
    @RequestMapping(value = "save_add_community_guide")
    @ResponseBody
    public void addGuide( Guide guide, HttpServletResponse response, HttpServletRequest request ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "保存成功";

        try {
            //【1】校验参数
            String imgUrl = request.getParameter( "imageUrl" );
            if ( StringUtils.isBlank( guide.getGuideName() ) || StringUtils.isBlank( imgUrl ) ) {
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", "" ) );
                return;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute(SessionKey.SESSION_USER_INFO);
            if ( user == null ) {
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return;
            }

            //【3】执行保存指南类别
            guide.setUserId( user.getId() );
            guideService.saveAddGuide( guide,imgUrl );

        } catch ( Exception e ) {
            log.error( "保存指南类别异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "保存失败";
        }
        RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( code, message, "community_guide_list", "", "closeCurrent", "" ) );
    }

    /**
     * 跳转到编辑指南类别页面
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "to_edit_community_guide")
    public String guideDetail( HttpServletRequest request, HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if ( requestMap.get("id") == null ) {
                return null;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【3】查询指南类别数据
            requestMap.put("userId", user.getId());
            GuideVo guideVo = guideService.guideDetail(requestMap);
            request.setAttribute("guide", guideVo);
            if (guideVo == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "数据不存在", "", "", "", ""));
                return null;
            }

            //【6】查询社区封面
            Map<String,Object> queryImageMap = new HashedMap();
            queryImageMap.put( "referId",requestMap.get( "id" ) );
            queryImageMap.put( "saveType", SaveImageType.COMMUNITY_GUIDE );
            List<ImageUrl> imageUrls = imageService.images( queryImageMap );
            if( CollectionUtils.isNotEmpty( imageUrls ) ){
                request.setAttribute( "image",imageUrls.get(0) );
            }

        } catch ( Exception e ) {
            log.error( "查询指南类别失败: " + e.getMessage() );
            RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "查询失败", "", "", "", ""));
        }

        return "community/guide/edit";
    }

    /**
     * 更新指南类别
     *
     * @param guide
     * @param response
     */
    @RequestMapping(value = "save_edit_community_guide")
    @ResponseBody
    public void updateGuide( Guide guide, HttpServletResponse response, HttpServletRequest request ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "更新成功";

        try {

            //【1】校验参数
            String imageUrl = request.getParameter( "imageUrl" );
            if ( StringUtils.isBlank( guide.getGuideName() ) || StringUtils.isBlank( imageUrl ) ) {
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", "" ) );
                return;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if (user == null) {
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return;
            }

            //【3】执行更新指南类别
            guide.setUserId( user.getId() );
            guideService.saveUpdateGuide( guide,imageUrl );

        } catch ( Exception e ) {
            log.error( "更新指南类别异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "更新失败";
        }
        RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( code, message, "community_guide_list", "", "closeCurrent", "" ) );
    }

    /**
     * 跳转到添加指南类别的页面
     * @return
     */
    @RequestMapping(value = "to_add_community_guide")
    public String toAddGuide(){

        return "community/guide/add";
    }
}
